package com.cirkana.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;

public abstract class CirkanaConfig {

	protected Properties loadProperties(InputStream propertiesInputStream) throws CirkanaConfigException {
		Properties p = new Properties();
		try {
			p.load(propertiesInputStream);
			return p;
		} catch (IOException e) {
			throw new CirkanaConfigException(e);
		}
	}

	protected String extractStringProperty(Properties properties, String propertyName) throws CirkanaConfigException {
		String value = extractStringProperty(properties, propertyName, "");
		if ("".equals(value))
			throw new CirkanaConfigException(propertyName, "");
		return value;
	}

	protected String extractStringProperty(Properties properties, String propertyName, String defaultValue) throws CirkanaConfigException {
		return properties.getProperty(propertyName, defaultValue);
	}

	protected int extractIntegerProperty(Properties properties, String propertyName) throws CirkanaConfigException {
		int value = extractIntegerProperty(properties, propertyName, Integer.MIN_VALUE);
		if (Integer.MIN_VALUE == value)
			throw new CirkanaConfigException(propertyName, "");
		return value;
	}

	protected int extractIntegerProperty(Properties properties, String propertyName, int defaultValue) throws CirkanaConfigException {
		String value = properties.getProperty(propertyName, Integer.toString(defaultValue));
		try {
			return Integer.parseInt(value);
		} catch (Exception e) {
			throw new CirkanaConfigException(e, propertyName, value);
		}
	}

	protected boolean extractBooleanProperty(Properties properties, String propertyName, boolean defaultValue) throws CirkanaConfigException {
		String value = extractStringProperty(properties, propertyName, defaultValue ? "TRUE" : "FALSE");
		return value.toUpperCase().equals("TRUE");
	}

	protected ArrayList<String> extractStringListProperties(Properties properties, String propertyName) throws CirkanaConfigException {
		int iii = 0;
		ArrayList<String> list = new ArrayList<String>();
		String value = extractStringProperty(properties, propertyName + "." + ++iii, "");
		while (!"".equals(value)) {
			list.add(value);
			value = extractStringProperty(properties, propertyName + "." + ++iii, "");
		}
		return list;
	}

}
